<template>
  <div class="qrcode">
    <!-- <i class="iconfont icon-icon_close" @click="closeScan"></i> -->
    <van-popup v-model="show" @close="closePopup" closeable position="bottom" :style="{ height: '100vh' }">
      <div class="readerBox">
        <div id="reader"></div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { Html5Qrcode } from "html5-qrcode";
export default {
  model: {
    prop: "show",
    event: "onEmit"
  },
  props: ["show"],
  data() {
    return {};
  },
  created() {
    this.getCameras();
  },
  beforeDestroy() {
    this.stop();
  },
  methods: {
    closePopup() {
      this.$emit("err");
    },
    getCameras() {
      Html5Qrcode.getCameras()
        .then(devices => {
          if (devices && devices.length) {
            this.html5QrCode = new Html5Qrcode("reader");
            this.start();
          }
        })
        .catch(err => {
          this.html5QrCode = new Html5Qrcode("reader");
          this.error = "ERROR: 您需要授予相机访问权限";
          this.$emit("err", this.error);
        });
    },
    start() {
      this.html5QrCode
        .start(
          { facingMode: "environment" },
          {
            fps: 2,
            // qrbox: { width: 250, height: 200 }
          },
          (decodedText, decodedResult) => {
            this.$emit("ok", decodedText);
          }
        )
        .catch(err => {
          this.$emit("err", err);
        });
    },
    stop() {
      this.html5QrCode
        .stop()
        .then(ignore => {
          // QR Code scanning is stopped.
          console.log("QR Code scanning stopped.");
        })
        .catch(err => {
          // Stop failed, handle it.
          console.log("Unable to stop scanning.");
        });
    },
    closeScan() {
      this.$emit("err");
    }
  }
};
</script>

<style lang="scss" scoped>
// .qrcode {
//   position: absolute;
//   top: 0;
//   left: 0;
//   height: 100%;
//   width: 100%;
//   // background: rgba($color: #000000, $alpha: 0.48);
//   background: #000000;
//   .icon-icon_close {
//     font-size: 1rem;
//     color: #ffff;
//     position: absolute;
//     left: 0;
//   }
// }
.readerBox {
  position: relative;
  height: 100%;
  width: 100%;
  background: #000000;
  #reader {
    position: absolute;
    top: 10%;
    left: 0;
    height: 90vh;
    width: 100%;
  }
}
</style>
